package me.eleme.anubis.openapi.oauth;

import me.eleme.anubis.openapi.api.exception.ServiceException;
import me.eleme.anubis.openapi.config.Config;
import me.eleme.anubis.openapi.config.Constants;
import me.eleme.anubis.openapi.config.oauth.response.Token;
import me.eleme.anubis.openapi.oauth.impl.DefaultOauthClient;
import me.eleme.anubis.openapi.oauth.request.ServerRefreshTokenRequest;
import me.eleme.anubis.openapi.oauth.request.ServerTokenRequest;
import me.eleme.anubis.openapi.utils.SignatureUtil;

/**
 * @author liuzhiyong
 */
public class OauthClient {

    private Config config;


    private IoauthClient ioAuthClient = null;


    public OauthClient(Config config){
        this.config = config;
    }


    /**
     * 授权码模式获取Token
     *
     * @param authCode     授权码
     * @param redirectUri 重定向地址
     * @return Token信息
     */
    public Token getTokenByCode(String authCode, String merchantId,String redirectUri) throws ServiceException {
        ioAuthClient = new DefaultOauthClient(config, Constants.TOKEN_URL);
        ServerTokenRequest serverTokenRequest = new ServerTokenRequest(config);
        serverTokenRequest.setCode(authCode);
        serverTokenRequest.setMerchantId(merchantId);
        serverTokenRequest.setRedirectUri(redirectUri);
        serverTokenRequest.setTimestamp(""+ System.currentTimeMillis());
        String sortedParamsStr = SignatureUtil.sortGetTokenParams(
                config.getAppId(), merchantId, System.currentTimeMillis() +"",authCode);
        // 计算签名
        String signature = SignatureUtil.genSignature(config.getSecretKey(), sortedParamsStr);
        serverTokenRequest.setSignature(signature);
        Token token = ioAuthClient.execute(serverTokenRequest,Token.class);
        return token;
    }

    public Token getTokenByRefreshToken(String merchantId,String refreshToken) throws ServiceException  {
        ioAuthClient = new DefaultOauthClient(config, Constants.REFRESH_TOKEN_URL);
        ServerRefreshTokenRequest refreshTokenRequest = new ServerRefreshTokenRequest(config);
        refreshTokenRequest.setRefreshToken(refreshToken);
        refreshTokenRequest.setMerchantId(merchantId);
        refreshTokenRequest.setTimestamp(""+ System.currentTimeMillis());
        String sortedParamsStr = SignatureUtil.sortRefreshTokenParams(
                config.getAppId(), merchantId, System.currentTimeMillis() +"",refreshToken);
        // 计算签名
        String signature = SignatureUtil.genSignature(config.getSecretKey(), sortedParamsStr);
        refreshTokenRequest.setSignature(signature);
        Token token = ioAuthClient.execute(refreshTokenRequest,Token.class);
        return token;
    }
}
